var ITDC  = {
    
    site_url : false,
    base_url : false,
    resize_timer : false,
    
    
    init : function(){        
        
        ITDC.setFancyBoxes();
        
        //setting navigation show/hide events
        $('.nav_switcher').click(function(){
            
            ITDC.NavigationSwitch();
            
        })
       
       
        /*Set Tooltips for navigation menu*/
        $("#NavigationBar li.selected").removeAttr('title');
        if($.cookie('Leftmenu_view')=='show'){
            $("#NavigationBar li").not('.selected').tipTip({
            
            });
        }
        
        //$("#NavigationBar li img").tipTip();
        
        ITDC.SetContentFlexible();
        
        
        $('#ContentWrapper').fadeIn(300);
        this.UserProfile();
        this.AdvancedSearch();
        this.InterfaceLang();
        this.checkClientWidth();
    },
    

    checkClientWidth : function (){
    	
    	window.onresize = function() {
    	clearTimeout(this.resize_timer);
            this.resize_timer = setTimeout(function(){    
    			var clientWidth = $(window).width();
    			ITDC.NavigationSwitch(clientWidth);
            },500)
	    }    	
    },
    AdvancedSearch : function (){
    	$('#srch_adv_opener').click(function(){
        	$('#srch_adv').slideToggle();
        })
    },
    InterfaceLang : function (){
    	
    },
    NavigationSwitch : function(clientWidth){
    	console.log(clientWidth);
    	animation_distance = '-173px';
    	if($.cookie('Leftmenu_view')=='show' && !clientWidth){
            /*Here mustHide left menu*/
            ITDC.HideLeftMenu();
        }else if($.cookie('Leftmenu_view')=='hide' && !clientWidth)  {
            /*Here must Show left menu*/
            //Changing icon 
           ITDC.ShowLeftMenu();
        } else if(clientWidth) {
        	if(clientWidth< 1000) {
        		ITDC.HideLeftMenu();
        	} else {
        		ITDC.ShowLeftMenu();
        	}
        }
        
    },
    HideLeftMenu : function (){
    	$('#NavigationBar').animate({'margin-left':animation_distance},300,function(){
        	//Changing icon 
            $('.nav_switcher').removeClass('SwitchLeft').addClass('SwitchRight');
            //setting hidden class for active link
            $('#NavigationBar .selected').addClass('hidden');
            $('#AdminLogo').attr('src',ITDC.base_url+'/Images/adm/layout/itdc_logo_min.png').removeClass('logo').addClass('logo_min');
            $('#AdminLogoTxt').hide(); 
            $('#AdminLogoTxt').css({'width': '203px'});                
        })
        $('#AdminContent').animate({'width':$('body').width()*.95,'margin-left':'37px'},300);
        $.cookie('Leftmenu_view', 'hide',  { expires: 1000, path: '/' })
        
        $("#NavigationBar li").not('.selected').tipTip({
            
        });
        
    },
    ShowLeftMenu : function (){
    	$('.nav_switcher').removeClass('SwitchRight').addClass('SwitchLeft');
        $('#NavigationBar .selected').removeClass('hidden');
        $('#AdminContent').animate({'width':$('body').width()*.84,'margin-left':'210px'},300);
        $('#NavigationBar').animate({'margin-left':'0px'},300)
        $('#AdminLogo').attr('src',ITDC.base_url+'/Images/adm/layout/logo.png').removeClass('logo_min').addClass('logo');
        $('#AdminLogoTxt').show();
        $('#AdminLogoTxt').css({'width': '173px'});
        $.cookie('Leftmenu_view', 'show',  { expires: 1000, path: '/' })
        $('#NavigationBar li').removeClass('hidden');
    },
    
    SetContentFlexible : function(){
        
        $(window).resize(function(){
            
            
            win_width = parseInt($(this).width());
            
            
            if($.cookie('Leftmenu_view')=='show'){
                
                $('#AdminContent').css({'width':(win_width-230)})
                
            }else{
                $('#AdminContent').css({'width':win_width-40})
            }
        });
        $(window).resize();
        
    }, 
    
    
    /** Login Form  Functions*****************************/
    
    LoginFocus : function (){
        $('#usname').focus();
        this.ChangePasswordType();
        this.RememberPassNotify();
    },
   
    /** Edit User Profile *****************************/
    UserProfile : function (){
    	$('.AccauntName').mouseover(function(e){
       		e.preventDefault();
       		e.stopPropagation();
       		$('.user_profile').show();
        });
		$('.user_profile').mouseout(function(e){
			e.preventDefault();
       		//$(this).hide();
       	});
       	$('.AccauntName').click(function(){
       		window.location.href=$('.user_profile a').first().attr('href');
       		return false;
       	});
  		$(document).click(function (event) {
    		$('.user_profile').hide();
		});
    },
    
    
    ChangePasswordType : function (){
        
        $('.ShowPassword').unbind('click');
        
        $('.ShowPassword').click(function(){
            
            var oldinput_data = {
                    'class' : $('#uspw').attr('class'),
                    'id' : $('#uspw').attr('id'),
                    'name' : $('#uspw').attr('name'),
                    'value' : $('#uspw').val()
            }
            
            
            if($('#uspw').attr('type')=='password'){
                
                oldinput_data.type = 'text';    
                
                $('#uspw').remove();
                
                $('<input/>',oldinput_data).insertBefore('.ShowPassword');
                
                $('.ShowPassword').html(ITDC.hide_pass);
                    
            }else{
                
                oldinput_data.type = 'password';    
                
                $('#uspw').remove();
                
                $('<input/>',oldinput_data).insertBefore('.ShowPassword');
                
                $('.ShowPassword').html(ITDC.show_pass);
                
            }
            
            $('#uspw').focus();
                
        });
        
    },
    
    RememberPassNotify : function (){
        $('#remember').change(function(){
            
            if($(this).attr('checked')!='checked'){
                $('#RememberNotification').fadeOut();
                return false;
            }
            
            if(!$('#RememberNotification').attr('id')){
            
                $('<div/>',{
                    'id' : 'RememberNotification',
                    'class' : 'RememberNotification'
                }).appendTo($(this).parent()).
                html(ITDC.remember_note).
                fadeIn();
                $('.login_arrow').show();
                $(document).unbind('mousedown');
            
                $(document).mousedown(function(){
                    $('#RememberNotification').fadeOut();
                    $('.login_arrow').hide();
                })
            
            }else{
                $('#RememberNotification').fadeIn();
            }
            
            
        })
        
    },
    
    
    setLoginTimer : function (){
        
        ITDC.LoginPromtTime =  setInterval(function(){
            
            remine_time = parseInt($('.TimeLoader strong').html());
            
            if(remine_time==0){
                
                top.location.href = ITDC.site_url+'/login/';
                
            }else{
                
                $('.TimeLoader strong').html(remine_time-1);
                
            }
            
        },1000)
        
    },
    
    
    BrowserNotify : function (){
        $('<div/>',{
            'id' : 'confirmOverlay'
        }).appendTo('body').hide();
        
        markup = [
			'<div id="BrowserNotify">',
			'<h1>თქვენ იყენებთ ბრაუზერის მოძველებულ ვერსიას! <br /> იმისათვის, რომ უკეთ შეძლოთ საიტით სარგებლობა, გთხოვთ გადმოიწეროთ ახალი ვერსია:</h1><ul>',
            '<li><a href="" tagret="_blank"><img src="'+ITDC.base_url+'/Images/adm/icons/browsers/ie.png" alt=""></a><p>IE</p></li>',
            '<li><a href="" tagret="_blank"><img src="'+ITDC.base_url+'/Images/adm/icons/browsers/chrome.png" alt=""></a><p>CHROME</p></li>',
            '<li><a href="" tagret="_blank"><img src="'+ITDC.base_url+'/Images/adm/icons/browsers/ff.png" alt=""></a><p>FIREFOX</p></li>',
            '<li><a href="" tagret="_blank"><img src="'+ITDC.base_url+'/Images/adm/icons/browsers/opera.png" alt=""></a><p>OPERA</p></li>',
            '<li><a href="" tagret="_blank"><img src="'+ITDC.base_url+'/Images/adm/icons/browsers/safari.png" alt=""></a><p>SAFARI</p></li>',
            '</ul>',
            '<button class="button_canecl">SKIP<span></span></button></div>',
			].join('');
       
       $(markup).appendTo('#confirmOverlay');
       
       $('#confirmOverlay .button_canecl').click(function(){
            $('#confirmOverlay').remove();    
       })
       
       $('#confirmOverlay').fadeIn(200);
        
    },
    
    
    // Init fancy boxes    
    setFancyBoxes : function (){
        
        $(".fancy").fancybox();		
    	$('.fancyFrame').fancybox({
    			type				: 'iframe',
    			width				: 980,
    			height				: 470
    	});
    
    }
    
}





$(function () {
//switch lang on dropdown selection change
	$("#lang_select").change(function(e){
			  window.location = $(this).val();
    });
});




$(function(){
		   
	
	
    //login lang
    $('.switchTo').click(function(){                       
        $('.lang-setter').find('p').each(function(){
            $(this).removeClass('lang_btn_active');
        });
        
        $('#envi-msg').css('display', 'none');
        
        var msg = new Array();
        
		msg['ge'] = 'áƒ˜áƒœáƒ¢áƒ”áƒ áƒ¤áƒ”áƒ˜áƒ¡áƒ˜áƒ¡ áƒ”áƒœáƒ� - áƒ¥áƒ�áƒ áƒ—áƒ£áƒšáƒ˜';
        msg['en'] = 'Interface language - English';        
        
        $(this).addClass('lang_btn_active');
        
		$('#flag').attr('class', '');
        $('#flag').addClass($(this).attr('id'));
        $('#envi-msg').html(msg[$(this).attr('id')]);
        $('#envi-msg').fadeIn('slow');
    	
		$.cookie('interface') == $.cookie('interface', $(this).attr('id'), { expires: 10000, path: '/' });	
		console.log($.cookie('interface'));
	});
	
	
	
	// show/hide left pane	   
	$('#show_hide_nav').click(function(){
			
			var $LeftBar 	= $(this).parent();
			var $wrapper 	= $("#wrapper");
			var $wrapHead	= $("#wrap_head");

			
			//animate left block
			$LeftBar.animate({
				marginLeft: parseInt($LeftBar.css('marginLeft')) !== 0 ? 0 : -155	
			});				
			
			//animate content wrapper
			$wrapper.animate({
				marginLeft: parseInt($wrapper.css('marginLeft')) !== 80 ? 80 : 230	
			});
			
			//animate page title
			$wrapHead.animate({
				marginLeft: parseInt($wrapHead.css('marginLeft')) == 79 ? 220 : 79			   
							   });
			// logo animation			
			/*
			if($("#logo").css("visibility") == "hidden"){
					$("#logo").css('visibility', 'visible');
			}else{
					$("#logo").css('visibility', 'hidden');
				 }
			*/

			// show/hide button icon change
			$(this).find('img').attr('icon')	== 'rewind' ? $(this).html('<img src="http://'+window.location.hostname+'/Images/icons/control_fastforward.png" icon="forward" align="absmiddle" />') : $(this).html('<img src="http://'+window.location.hostname+'/Images/icons/control_rewind.png" align="absmiddle" icon="rewind" />') ;
			$.cookie('Leftmenu_view')			== 'hidden' ? $.cookie('Leftmenu_view', 'show',  { expires: 1000, path: '/' }) : $.cookie('Leftmenu_view', 'hidden', { expires: 10000, path: '/' });	
				
		});
	});




function initFlashUpload(url,cont_id,exts)
{
	
	var uploader = new plupload.Uploader({
		runtimes : 'html5,html4',
		browse_button : 'pickfiles',
		container : 'container',
		max_file_size : '50mb',
		url : url+"/admin/books/flashUpload/" + cont_id,
		filters : [
			{title : "Allowed Files", extensions : exts}
		],
	});

	uploader.bind('Init', function(up, params) {
		//$('#filelist').html("<div>Current runtime: " + params.runtime + "</div>");
	});

	$('#uploadfiles').click(function(e) {
		uploader.start();
		e.preventDefault();
	});

	uploader.init();

	uploader.bind('FilesAdded', function(up, files) {
		$.each(files, function(i, file) {
			$('#filelist').append(
				'<div id="' + file.id + '">' +
				file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
			'</div>');
		});

		up.refresh(); // Reposition Flash/Silverlight
	});

	uploader.bind('UploadProgress', function(up, file) {
		$('#' + file.id + " b").html(file.percent + "%");
	});

	uploader.bind('Error', function(up, err) {
		$('#filelist').append("<div>Error: " + err.code +
			", Message: " + err.message +
			(err.file ? ", File: " + err.file.name : "") +
			"</div>"
		);

		up.refresh(); // Reposition Flash/Silverlight
	});

	uploader.bind('FileUploaded', function(up, file) {
		$('#' + file.id + " b").html("100%");
	});
	
		
}

function generatePass(length,alpha_val,character_val) {
  var alpha	= {1:"abcdefghijklmnopqrstuvwxyz",2:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",3:"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};
  var character = {1:"1234567890",2:'\'\'"~!@"#$%^&*()_+|{}:?><,./;][\=-',3:'\'\'"~!@"#$%^&*()_+|{}:?><,./;][\=-1234567890'}; 
  var pass	= "";
  var chars	= alpha[alpha_val]+character[character_val];
  var index;
  for(var x=0; x<length; x++) {
    index = Math.floor(Math.random() * (alpha[alpha_val].length + character[character_val].length));
    pass += chars.charAt(index);
  }
  return pass;
}




$(document).ready(function(){
    // console.log($('table tr[class="regexp {level-[0-9]} "]'));
     /* Menu Sort - Drag And Drop
     * *
     */
    /*
    function generateIds(ids){
        var arr = [];
        ids.each(function(index,value) {
            arr[index] = this.getAttribute('id'); 
        });
        return arr;
    }
    var old = generateIds($('#items').children());
    $('#items').tableDnD({
        onDrop: function(table, row) {
            var data = {'old' : old, 'new' : generateIds($('#items').children())};
            //console.log(data);
            $.ajax({
            url: "cats/sort",
            type: "POST",
            data :data,
                success : functfiion() {

                }
            });
        }
    });
    */
    
    $('#pass_generate').live("click",function(){
	var pass_length = $('#pass_length').val();
	if(pass_length) {
	    if(pass_length < 7 || pass_length> 18) {
		$('#pass_length').removeClass('pass_length');
		$('#pass_length').addClass('pass_length_red');
		$('#pass_length').val(pass_length);
		return false;
	    } else {
		if($('#pass_length').hasClass('pass_length_red')) {
		    $('#pass_length').removeClass('pass_length_red');
		    $('#pass_length').addClass('pass_length');
		}
	    }
	} else {
	    pass_length = 7;
	}
	var alpha	    = $('input:radio[name="pass_alpha"]:checked').val();
	var character   = $('input:radio[name="pass_character"]:checked').val();
	$('#user_pass').val(generatePass(pass_length,alpha,character));
    });
    $('#adv_options').click(function(){
	$('.adv_pass_bl').slideToggle();
    });
    
   
    
});
